package schoolmath.web.services;

import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import schoolmath.web.entities.User;

import javax.inject.Inject;
import java.util.Arrays;
import java.util.HashSet;

public class SchoolmathRealmImpl extends AuthorizingRealm implements SchoolmathRealm {

	private static Logger logger = LoggerFactory.getLogger(SchoolmathRealmImpl.class);
	@Inject
	private Session session;

	public SchoolmathRealmImpl() {
		HashedCredentialsMatcher credintialsMatcher = new HashedCredentialsMatcher();
		credintialsMatcher.setHashAlgorithmName("MD5");
		this.setCredentialsMatcher(credintialsMatcher);
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		User user = (User) principals.getPrimaryPrincipal();
		return new SimpleAuthorizationInfo(new HashSet<>(Arrays.asList(user.getRole().getName())));
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken authToken = (UsernamePasswordToken) token;
		String username = authToken.getUsername();
		User user;

		user = (User) session.createCriteria(User.class)
				.add(Restrictions.eq("login", username))
				.uniqueResult();

		if (user == null) {
			throw new UnknownAccountException();
		}

		return new SimpleAuthenticationInfo(user, user.getPassword(), "database");
	}

}
